package com.mars.security.app.social;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.ConnectionData;
import org.springframework.social.connect.ConnectionFactoryLocator;
import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.WebRequest;

import java.util.concurrent.TimeUnit;

/**
 * @author masisi
 * @date 2024/10/8 14:04
 * @Description
 */
@Component
public class AppSingUpUtils {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UsersConnectionRepository usersConnectionRepository;
    @Autowired
    private ConnectionFactoryLocator connectionFactoryLocator;

    // 绑定用户
    public void doPostSignUp(WebRequest request, String userId){
        String key = getKey(request);
        if (!redisTemplate.hasKey(key)){
            throw new IllegalArgumentException("无法找到缓存的用户社交信息");
        }

        ConnectionData connectionData = (ConnectionData)redisTemplate.opsForValue().get(key);
        Connection<?> connection = connectionFactoryLocator.getConnectionFactory(connectionData.getProviderId())
                .createConnection(connectionData);
        usersConnectionRepository
                .createConnectionRepository(userId)
                .addConnection(connection);

        redisTemplate.delete(key);
    }

    // 保存用户信息
    public void saveConnectionData(WebRequest request, ConnectionData connectionData){
        redisTemplate.opsForValue().set(getKey(request),connectionData,10, TimeUnit.MINUTES);
    }

    private String getKey(WebRequest request) {
        String deviceId = request.getHeader("deviceId");
        if (StringUtils.isBlank(deviceId)) {
            throw new IllegalArgumentException("deviceId is not null");
        }
        return "imooc:security:social.connect." + deviceId;
    }
}
